package com.cygsunri.wisdompark.util;

import com.cygsunri.common.TuYaConstant;
import com.cygsunri.common.YaHeConstant;
import com.cygsunri.util.TimeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 有关涂鸦平台相关的web工具类
 **/
@Component
public final class TuYaWebUtil {

    /**
     * 原生字符串发送get请求
     *
     * @param url
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doGet(String url,String accessId,String accessSecret,String token) {
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpGet.setConfig(requestConfig);
        try {
            Map<String, Object> headerMap = getHeaderMap(accessId,accessSecret,token);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                    httpGet.setHeader(key, headerMap.get(key).toString());
                }
            }
            httpGet.setHeader("Content-type", "application/json");
            httpGet.setHeader("DataEncoding", "UTF-8");
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 原生字符串发送post请求
     *
     * @param url
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public static String doPost(String url, String jsonStr,String accessId,String accessSecret,String token) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        CloseableHttpResponse httpResponse = null;
        try {
            Map<String, Object> headerMap = getHeaderMap(accessId,accessSecret,token);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                    httpPost.setHeader(key, headerMap.get(key).toString());
                }
            }
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("DataEncoding", "UTF-8");
            httpPost.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 原生字符串发送put请求
     *
     * @param url
     * @param jsonStr
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doPut(String url,String jsonStr,String accessId,String accessSecret,String token) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        CloseableHttpResponse httpResponse = null;
        try {
            Map<String, Object> headerMap = getHeaderMap(accessId,accessSecret,token);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                    httpPut.setHeader(key, headerMap.get(key).toString());
                }
            }
            httpPut.setHeader("Content-type", "application/json");
            httpPut.setHeader("DataEncoding", "UTF-8");
            httpPut.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 发送delete请求
     *
     * @param url
     * @param jsonStr
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doDelete(String url, String jsonStr,String accessId,String accessSecret,String token) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpDelete.setConfig(requestConfig);
        CloseableHttpResponse httpResponse = null;
        try {
            Map<String, Object> headerMap = getHeaderMap(accessId,accessSecret,token);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                    httpDelete.setHeader(key, headerMap.get(key).toString());
                }
            }
            httpDelete.setHeader("Content-type", "application/json");
            httpDelete.setHeader("DataEncoding", "UTF-8");
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 生成签名sign
     *
     * @param message client_id + access_token + t将 client_id 、access_token 和当前请求的 13 位标准时间戳（t）拼接成字符串
     * @param secret
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    private static String getSign(String secret, String message) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
        return new HexBinaryAdapter().marshal(bytes).toUpperCase();
    }

    /**
     * 生成headerMap
     *
     * @param
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    private static Map<String, Object> getHeaderMap(String accessId,String accessSecret,String token) throws Exception {
        Map<String, Object> headerMap = new HashMap<>();
        Long time = DateUtil.nowMilliSeconds();
//        String nonce = UUID.randomUUID().toString().replaceAll("-","");
        String message = new String();
        if(StringUtils.isNotEmpty(token)){
            message = accessId+ token+time.toString();
        }else{
            message = accessId+ time.toString();
        }
        String sign = getSign(accessSecret, message);
        headerMap.put("client_id", accessId);
        headerMap.put("sign", sign);
        headerMap.put("sign_method", "HMAC-SHA256");
        headerMap.put("t", time);
        if(StringUtils.isNotEmpty(token)) {
            headerMap.put("access_token", token);
        }
//        headerMap.put("nonce", nonce);
//        headerMap.put("Signature-Headers", "access_token");
        return headerMap;
    }

}
